
#include "test.h"

using namespace Tester;

void Test::init() {
   try {
      checkpointcounter = 0;
      setUp();
   }catch(const std::exception &e){
      throw CriticalError("SetUp", e.what());
   }catch(...){
      throw CriticalError("SetUp");
   }
}

void Test::finish() {
   try {
      tearDown();
   }catch(const std::exception &e){
      throw CriticalError("TearDown", e.what());
   }catch(...){
      throw CriticalError("TearDown");
   }
}

void Test::setUp() {}
void Test::tearDown() {}


void Test::runTestMethod(TestMethod* testMethod, Result *result) {
   try{
      init();
      testMethod->run(result, this);
      finish();
   }catch(const CriticalError &e){
      result->error(testMethod->name(), e.name(), e.what());
   }
}

void Test::checkpoint() {
   ++checkpointcounter;
}

unsigned int Test::checkpoint_count() const {
   return checkpointcounter;
}

void Test::assertTrue(bool stm, int line){
   if(!stm) throw AssertFail("AssertTrue", line);
}

void Test::assertFalse(bool stm, int line){
   if(stm) throw AssertFail("AssertFalse", line);
}


void Test::add(TestMethod *testMethod) {
   methods.push_back(testMethod);
}

Test::Test(const char *name, const char *file) : name(name), file(file) {
   assert(name != 0);
   GlobalSuite::add(this);
}

void Test::run(Result *result) {
   std::list<TestMethod*>::iterator it = methods.begin();

   result->initTestCase(name, file);

   for ( ; it != methods.end() ; ++it ) {
      runTestMethod(*it,  result);
   }

   result->finishTestCase(methods.size());
}

Test::~Test() {
   std::list<TestMethod*>::iterator it = methods.begin();

   for ( ; it != methods.end() ; ++it ) {
      delete *it; 
   }
   methods.clear();
}
